/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.CustomerIOTRPortal;

import session.TX.GroupBuyCustomerSBRemote;
import entity.GroupBuyingItem;
import Web_Helper.Helper_PaymentValidator;
import entity.PurchasedItem;
import entity.PurchasedItem_GroupOn;
import entity.Users;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;
import session.TX.TransactionManagerSBRemote;
import session.TX.UsersSBRemote;

/**
 *
 * @author Lu Xiaodi
 */
@ManagedBean(name = "groupBuyCustManagedBean")
@ViewScoped
public class GroupBuyCustMB {
    
    @EJB
    private TransactionManagerSBRemote transactionManager;
    @EJB
    private UsersSBRemote userManager;
    @EJB
    private GroupBuyCustomerSBRemote gbManagerBean;
    private String purchaseStatusMSG = "DEFAULT";
    private GroupBuyingItem selectedItem;
    private Integer numberToBuy = 0;
    private String customerEmail;
    private Long customerId;
    private Double subtotal=0.0;

    /** Creates a new instance of GroupBuyCustMB */
    public GroupBuyCustMB() {
        customerId = getCustomerIdFromSession();
    }

    public List<GroupBuyingItem> getAvailableItems() {
//        System.out.println("Im Here");
        return gbManagerBean.getAvailableGBItem();
    }

    public Integer calculateDiscount(GroupBuyingItem item) {
        if (item == null) {
            return null;
        }
        return new Double((item.getOriginalPrice() - item.getOfferedPrice()) * 100
                / item.getOriginalPrice()).intValue();
    }

    public GroupBuyingItem getSelectedItem() {
        selectedItem = this.getItemFromSession();
        return selectedItem;
    }

    public void setSelectedItem(GroupBuyingItem selectedItem) {
        this.selectedItem = selectedItem;
    }

    public String getCustomerEmail() {
        return customerEmail;
    }

    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    public Integer getNumberToBuy() {
        return numberToBuy;
    }

    public void setNumberToBuy(Integer numberToBuy) {
        this.numberToBuy = numberToBuy;
    }

    public void handleNumberToBuyChange() {
        subtotal = selectedItem.getOfferedPrice() * numberToBuy;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        session.setAttribute("numberToBuy", numberToBuy);
    }

    public List<SelectItem> computeQuotaSeq() {
        System.out.println(selectedItem);
        List<Integer> quotas = gbManagerBean.getQuotaSeq(selectedItem, customerId);
        List<SelectItem> returnList = new ArrayList<SelectItem>();
        for (Integer i : quotas) {
            returnList.add(new SelectItem(i, i.toString()));
        }
        return returnList;
    }

    public Double getSubtotal() {
        return subtotal;
    }

    public Long getCustomerId() {
        return customerId;
    }

    public void setCustomerId(Long customerId) {
        this.customerId = customerId;
    }

    public List<PurchasedItem_GroupOn> customerGetGroupDeals() {
        String email = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("email").toString();
        return transactionManager.retrievePurchasedItemGroupon(email, null, false);
    }

    public String getPurchaseStatusMSG() {
        return purchaseStatusMSG;
    }

    public void setPurchaseStatusMSG(String purchaseStatusMSG) {
        this.purchaseStatusMSG = purchaseStatusMSG;
    }

    public void updateSelectedItem(GroupBuyingItem item) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        session.setAttribute("gbItem", item);
    }
    
    public GroupBuyingItem getItemFromSession() {
        return (GroupBuyingItem) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("gbItem");
    }
    
    public Long getCustomerIdFromSession() {
        return (Long)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("accountId");
    }

    //Perform validation of a payment
    public void validatePayment() {

        boolean validationResult = false;
        try {
            validationResult = Helper_PaymentValidator.validatePayment();
        } catch (IOException e) {
        }

        if (validationResult == true) {
            System.out.println("Payment Validation: SUCCESS");


            this.doTransactionLog();
            this.selectedItem = null; //Once finished, set the selected groupon to null

        }//end THEN block
        else {
            System.out.println("Payment Validation: FAIL");
        }

    }//------------------------------------------------------------------------------------------

    public void doTransactionLog() {
        
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        
        try{     
            selectedItem = (GroupBuyingItem) session.getAttribute("gbItem");
        }
        catch(NullPointerException e){
            System.out.println("No groupon detected in session");
            return;
        }
        try{     
            numberToBuy = (Integer) session.getAttribute("numberToBuy");
        }
        catch(NullPointerException e){
            System.out.println("No numbetToBuy detected in session");
            return;
        }
        

        
        String buyerEmail = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("email").toString();
        Long customerID = Long.valueOf(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("accountId").toString());

        //Find the customer
        List<Users> userList = userManager.getAllUser();



        double subtotal = numberToBuy * selectedItem.getOfferedPrice();


        System.out.println("Customer " + buyerEmail + " purchased a groupon.");
        Calendar transaction_timestamp = Calendar.getInstance();

        //generate the list of purchase items to put into the transaction entry
        //Since group buying items are bought one by one, the list only contains one purchase item
        List<PurchasedItem> purchasedItemList = new ArrayList<PurchasedItem>();

        PurchasedItem itemEntity = transactionManager.createPurchasedItem_GroupOn(
                selectedItem.getId(),
                selectedItem.getName(),
                selectedItem.getDescription(),
                transaction_timestamp,
                buyerEmail,
                selectedItem.getStakeholder().getName(),
                customerID,
                numberToBuy,
                subtotal);

        purchasedItemList.add(itemEntity);

        transactionManager.createTransactionEntry(
                transaction_timestamp,
                buyerEmail,
                0,
                subtotal,
                purchasedItemList);
        
        
        //Start compose status message for front end 
            //--------------------------------------------------------------
            NumberFormat formatter = new DecimalFormat("#0.00");
            purchaseStatusMSG =
                      "<h4>Customer: </h4>" + buyerEmail + "<br/>"
                    + "<h4>Timestamp: </h4>" + transaction_timestamp.getTime() + "<br/><br/>"
                    + "<h4>Subscribed to Group Deal: </h4><br/>"
                    + "<table border='0' cellspacing='6'>"
                    + "<col width='20%' /><col width='80%' />"
                    + "<tr> <td><h5>Seller: </h5></td>   <td>" + selectedItem.getStakeholder().getName() + "</td>"
                    + "<tr> <td><h5>Deal: </h5></td>   <td>" + selectedItem.getName() + "</td>"
                    + "<tr> <td><h5>Description: </h5></td>   <td>" + selectedItem.getDescription() + "</td>"
                    + "<tr> <td><h5>Coupons Purchased: </h5></td>   <td>" + numberToBuy + "</td>"
                    + "<tr> <td><h5>Price per Coupon: </h5></td>   <td>" + selectedItem.getOfferedPrice() + "</td>"
                    ;        


            purchaseStatusMSG = purchaseStatusMSG + "</table>";
            //End compose status message
        //--------------------------------------------------------------
        
        
        
        
        
        session.removeAttribute("gbItem");
        session.removeAttribute("numberToBuy");
    
    }
}